package com.easyOrder.core.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;

@SuppressWarnings("restriction")
public class Base64 {
	public static String encode(String s, boolean forUri) {
		try {
			return encode(s.getBytes("utf-8"), forUri);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String encode(byte[] bytes, boolean forUri) {
		String encodeString = null;
		BASE64Encoder base64Encoder = new BASE64Encoder();
		try {
			encodeString = base64Encoder.encode(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (forUri) {
			encodeString = encodeString.replace('+', '_').replace('/', '-')
					.replace('=', '*');
		}
		return encodeString;
	}

	public static String decode(String s, boolean forUri) {
		if (forUri) {
			s = s.replace('_', '+').replace('-', '/').replace('*', '=');
		}
		String decodeString = null;
		BASE64Decoder base64Decoder = new BASE64Decoder();
		try {
			decodeString = new String(base64Decoder.decodeBuffer(s), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decodeString;
	}
}
